//
//  SlotsTableViewController.swift
//  Hyphenate-Demo-Swift
//
//  Created by JennyShi on 2018/4/19.
//  Copyright © 2018年 杜洁鹏. All rights reserved.
//

import UIKit
import os.log

class SlotsTableViewController: UITableViewController, Calendar1DetailDelegate{

    //声明代理回传数据的函数
    func didSaved(cuEvent0: CuEvent?, ownerGo0: String) {
        print("代理工作了，传回值\(ownerGo0)")
        //应该重新申请后端数据，然后刷新屏幕
        tableView.reloadData()
    }
    
    // 数据回传函数
    func myClosureMethod(cuEvent:CuEvent, ownerGo:String)->Void{
        //闭包类似于oc中的block或者可以理解成c语言中函数，只有当被调用的时候里面的内容才会执行
        print("Block 传值了==:\(cuEvent)")
        print("Block 传值了==:\(ownerGo)")
    }
    
    //传进来的选中日期、friendOwner、loginOwner和类型：0-match，1-free
    var dateTitle : String?
    var friendOwner : String?
    var loginOwner : String?
    var matchOrFree = 0
    
    //slots显示数组
    var slotsArr = [Slot]()
    var slotsDateArr = [[Date]]()

    //屏幕不含状态栏的大小
    var screenWidth : CGFloat = 0.0

    var dateFormatter = DateFormatter()
    var fromDate = Date()
    var toDate = Date()

    override func viewDidLoad() {
        super.viewDidLoad()

        //获取屏幕大小
        let screenApplicationBounds:CGRect = self.view.bounds
        
        screenWidth = screenApplicationBounds.width
        
        navigationItem.title = (matchOrFree == 0 ? "match    " : "free    ") + (friendOwner == nil ? "" : friendOwner!)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: (dateTitle == nil ? "" : dateTitle!), style: UIBarButtonItemStyle.plain, target: self, action: nil)
        
        let cellIdentifier:String = "SlotsTableViewCell"
        self.tableView.register(EventListTableViewCell.self, forCellReuseIdentifier: cellIdentifier)

        getSlotsFromBackend(matchOrFree: matchOrFree)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return slotsArr.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = tableView.cellForRow(at: indexPath)
        if cell == nil {
            cell = SlotsTableViewCell()
        }

//        let cellIdentifier = "SlotsTableViewCell"
//        var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? SlotsTableViewCell

        let slot = slotsArr[indexPath.row]
        
        //定义控件并赋值
        let fromLabel =  UILabel(frame: CGRect.zero)
        fromLabel.translatesAutoresizingMaskIntoConstraints = false
        fromLabel.text = slot.estartTime

        let toLabel =  UILabel(frame: CGRect.zero)
        toLabel.translatesAutoresizingMaskIntoConstraints = false
        toLabel.text = "To    " + slot.eendTime
        
        cell?.layer.masksToBounds = true
        cell?.contentView.addSubview(fromLabel)
        cell?.contentView.addSubview(toLabel)
        
        //添加控件约束。创建一个控件数组，把各个list的元素加进来并设置约束，控件宽度根据屏幕宽度计算。
        let views = ["fromLabel":fromLabel, "toLabel":toLabel]
        
        let widthEverage : Int = (Int(screenWidth) - 100)/2
        let csH1 : String = "H:|-80-[fromLabel(\(widthEverage-40))]-15-[toLabel(\(widthEverage+20))]-35-|"
        cell?.contentView.addConstraints(NSLayoutConstraint.constraints(
            withVisualFormat: csH1, options: [], metrics: nil,
            views: views))
        let csV1 : String = "V:|-0-[fromLabel(40)]-0-|"
        cell?.contentView.addConstraints(NSLayoutConstraint.constraints(
            withVisualFormat: csV1, options: [], metrics: nil,
            views: views))
        let csV2 : String = "V:|-0-[toLabel(40)]-0-|"
        cell?.contentView.addConstraints(NSLayoutConstraint.constraints(
            withVisualFormat: csV2, options: [], metrics: nil,
            views: views))

        return cell!
    }

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath)
        -> CGFloat {
            return 40
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: "slotsToCreateEvent", sender: self)
    }

    // MARK: - Navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        super.prepare(for: segue, sender: sender)
        switch(segue.identifier ?? "") {
        case "slotsToCreateEvent":
            let eventListDetailViewController = segue.destination as? Calendar1Detail
            let indexPath = tableView.indexPathForSelectedRow
            let selectedSlot = slotsArr[(indexPath?.row)!]
            eventListDetailViewController?.slot = selectedSlot
            eventListDetailViewController?.sourceViewControllerType = 3
            //代理返回值用
            eventListDetailViewController?.delegate = self
            //闭包返回值用
            eventListDetailViewController?.myClosure = myClosureMethod
            os_log("Go to detail", log: OSLog.default, type: .debug)
        default:
            fatalError("Unexpected Segue Identifier; \(String(describing: segue.identifier))")
        }
    }

    //MARK: Private Methods
    
    //根据free和match分别取后端的slots数据
    private func getSlotsFromBackend(matchOrFree : Int) {
        
        var urlstr : String = ""
        
        switch matchOrFree {
        case 0:     //match
            print("match000")
            urlstr = "slots?slotType=Match&user1=" + loginOwner! + "&user2=" + friendOwner! + "?date=" + dateTitle!
        case 1:     //free
            print("free111")
            urlstr = "slots?slotType=Free&user1=" + loginOwner! + "&user2=" + friendOwner! + "?date=" + dateTitle!
        default:
            urlstr = "slots?slotType=Match&user1=" + loginOwner! + "&user2=" + friendOwner! + "?date=" + dateTitle!
        }
        
        getSlots(urlString: urlstr)
        
    }
    
    private func getSlots(urlString : String) {
        
        let cuHTTP = CUHTTP.instance()
        
        cuHTTP.makeGetData(url: urlString, success: {response in
            print("Response String: \(String(describing: response?.result.value))")
            print(response?.response?.statusCode ?? "??")      //成功时，返回200
            //将response.result.value解析为字典并写入数组
            if let value = response?.result.value {
                let data = value.data(using: String.Encoding.utf8)! as NSData
                let json = try? JSONSerialization.jsonObject(with: data as Data,
                    options:.allowFragments) as! [String: [Any]]
                print(json ?? "??")
                //allSlots为所有的slots，是个数组，数组元素为字典
                let allSlots = json!["slots"]
                print(allSlots ?? "??")
                var startTime = ""
                var endTime = ""
                var slotDate = [Date]()
                //逐条写入显示数组slotsArr
                for loopSlot in allSlots! {
                    let loopE = loopSlot as! [String]
                    startTime = loopE[0].compare("24:00").rawValue == 0 ? "23:59" : (loopE[0].compare("00:00").rawValue == 0 ? "00:01" : loopE[0])
                    endTime = loopE[1].compare("24:00").rawValue == 0 ? "23:59" : (loopE[1].compare("00:00").rawValue == 0 ? "00:01" : loopE[1])
                    self.dateFormatter.dateFormat = "HH:mm"
                    self.fromDate = self.dateFormatter.date(from: startTime)!
                    self.toDate = self.dateFormatter.date(from: endTime)!
                    slotDate.removeAll()
                    slotDate.append(self.fromDate)
                    slotDate.append(self.toDate)
                    self.slotsDateArr.append(slotDate)
                    self.dateFormatter.dateFormat = "hh:mm a"
                    startTime = self.dateFormatter.string(from: self.fromDate)
                    endTime = self.dateFormatter.string(from: self.toDate)
                    guard let tmpSlot = Slot(startTime : startTime, endTime : endTime) else {
                        fatalError("Unable to instantiate CuEvent1")
                    }
                    self.slotsArr.append(tmpSlot)
                }
                print(self.slotsArr)
                print(self.slotsDateArr)
            }
            //因为是异步申请数据，所以要reload
            self.tableView.reloadData()
        }, failure:{ response in
                print(response)
                self.myAlert(message000: "get data failed")
            }
        )
    }

    func myAlert(message000 : String) {
        let alertController = UIAlertController(title: "",message: EnStatic.getWord(keyWord: message000), preferredStyle: .alert)
        let okAction = UIAlertAction(title: EnStatic.getWord(keyWord: "OK"), style: .default, handler: {
            action in
            print("ok clicked")
        })
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
}
